import { httpPost } from "./HttpUtil";
import { getCookie } from "./StorageUtil";


const BASE_URL = "http://localhost:12345";
// const BASE_URL = "http://117.72.76.205:12345";
// const BASE_URL = "http://westudy.life:12345";

export function isLogin() {
  var token = getToken();
  //检查是否单点登录
  const params = new URLSearchParams(window.location.search);
  const user = params.get("user");
  if (user !== null && user !== undefined && user !== "") {
    token = httpPost("/user/ssoLogin", { user: user }).data;
  }
  return httpPost("/user/isLogin", { token: token }).data;
}

export function isAdmin() {
  var token = getToken();
  return httpPost("/user/isAdminUser", { token: token }).data;
}

export function getToken() {
  return getCookie("token");
}

export function getBaseUrl() {
  return BASE_URL;
}

export function getPreviewUrl() {
  return BASE_URL+"/fileRecord/";
}

export function getUploadUrl() {
  return BASE_URL+"/fileRecord/upload";
}

export function getTrain() {
  return getCookie("train");
}

const sortTreeData = (tree: any) => {
  return tree
    .sort((a: any, b: any) => a.title.localeCompare(b.title, "zh-CN")) // 关键排序逻辑[1,2](@ref)
    .map((item: any) => {
      if (item.children) {
        return { ...item, children: sortTreeData(item.children) };
      }
      return item;
    });
};

const buildTree = (items: any, parentId: string) => {
  return items
    .filter((item: any) => item.pid === parentId)
    .map((node: any) => ({
      title: node.name, // Antd Tree 的显示字段
      value: node.id, // Antd Tree 的节点唯一标识
      children: buildTree(items, node.id),
    }));
};

export function getKnowledgeTree() {
  var data = httpPost("/knowledge/getKnowledgeList", {}).data;
  var result = buildTree(data, "root");
  // result = sortTreeData(result);
  return result;
}

export function getRandomElement(array: any[]) {
  return array[Math.floor(Math.random() * array.length)];
}

export function randomColor() {
  const brandColors = [
    "#5a1216",
    "#ed556a",
    "#b2cf87",
    "#876818",
    "#f6c430",
    "#15231b",
    "#126e82",
    "#a61b29",
    "#681752",
    "#525288",
    "#0eb0c9",
    "#1a6840",
    "#e16c96",
    "#36292f",
    "#ea7293",
    "#411c35",
    "#61649f",
    "#2e317c",
    "#2983bb",
    "#5cb3cc",
    "#474b4c",
    "#57c3c2",
    "#2c9678",
    "#d2d97a",
    "#1a3b32",
    "#a4aca7",
    "#a7a8bd",
    "#f03752",
    "#82111f",
    "#c8adc4",
    "#93b5cf",
    "#11659a",
    "#63bbd0",
    "#45b787",
    "#229453",
    "#41b349",
    "#bacf65",
    "#e2d849",
    "#fbda41",
    "#f8d86a",
    "#ffd111",
    "#fcb70a",
    "#fb8b05",
    "#f26b1f",
    "#f9723d",
    "#cf4813",
    "#ed5126",
    "#f34718",
    "#de2a18",
    "#eb261a"
  ];
  const getBrandColor = () =>
    brandColors[Math.floor(Math.random() * brandColors.length)];
  return getBrandColor();
}
